package com.dataart.training.crimequalification.service;

import com.dataart.training.crimequalification.entity.UserEntity;
import com.dataart.training.crimequalification.security.PasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

@Service
public class RegistrationServiceImpl implements RegistrationService {

    //----------------------------------------------------------------

    @Autowired
    private UserService userService;

    @Autowired
    private SaltSource saltSource;

    //----------------------------------------------------------------

    /**
     * Registers user with the provided details.
     *
     * @param username          username to register with
     * @param unencodedPassword "raw" password to register with
     * @param name              name to register with
     * @param email             email to register with
     * @param phoneNumber       phone number to register with
     * @return new user principal if registration performed successfully.
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */

    public UserEntity registerUser(String username, String unencodedPassword, String name, String email,
                                   String phoneNumber) throws UnsupportedEncodingException, NoSuchAlgorithmException,
            DataIntegrityViolationException {

        UserEntity newUser = new UserEntity(username, unencodedPassword, name, email, phoneNumber, false, 1);

        PasswordEncoder passwordEncoder = new PasswordEncoder();
        String salt = (String) saltSource.getSalt(userService.userEntityToUserDetails(newUser));
        String encodedPassword = passwordEncoder.encodePassword(unencodedPassword, salt);

        newUser.setPassword(encodedPassword);

        try {
            userService.addNewUser(newUser);
        } catch (DataIntegrityViolationException e) {
            throw e; // just to indicate where such exception is likely to occur
        }

        userService.assignRoleToUser(newUser, "ROLE_USER");

        return newUser;
    }

}
